import {
  Controller,
  Inject,
  Post,
  Get,
  Put,
  Body,
  Param,
  Query,
  Logger,
  Config,
  Del
} from "@midwayjs/core";
import { Context } from "@midwayjs/koa";
import { PrizeGroupService } from "../service/prize.group.service";
import { AuthService } from "../service/auth.service";
import {
  PrizeGroupCreateDto,
  PrizeGroupListQueryDto,
  PrizeGroupPageQueryDto,
  PrizeGroupUpdateDto
} from "../dto/prize.group.dto";
import { Utils } from "../utils";
import { ApiTags } from "@midwayjs/swagger";
import { ILogger } from "@midwayjs/logger";

@ApiTags(["抽奖活动管理"])
@Controller("/auth-api/prize-group")
export class PrizeGroupController {
  @Inject()
  prizeGroupService: PrizeGroupService;

  @Inject()
  authService: AuthService;

  @Inject()
  utils: Utils;

  @Inject()
  ctx: Context;

  @Logger()
  logger: ILogger;

  @Config("jwtCookieKey")
  jwtCookieKey: string;

  /**
   * 获取当前用户信息
   */
  private async getCurrentUser() {
    const token = this.ctx.cookies.get(this.jwtCookieKey);
    const userResult = await this.authService.get_current_user(token);
    if (!userResult.success || !userResult.data) {
      throw new Error("用户未登录");
    }
    return userResult.data;
  }

  /**
   * 创建抽奖活动
   */
  @Post("/")
  async create(@Body() dto: PrizeGroupCreateDto) {
    try {
      const user = await this.getCurrentUser();
      const data = await this.prizeGroupService.createPrizeGroup(
        dto,
        user.userId,
        user.account
      );
      return this.utils.response.success({ data });
    } catch (error) {
      this.logger.error("创建抽奖活动失败", error);
      return this.utils.response.fail({ message: "创建抽奖活动失败" });
    }
  }

  /**
   * 抽奖活动列表（不分页）
   */
  @Get("/list")
  async list(@Query() query: PrizeGroupListQueryDto) {
    try {
      const data = await this.prizeGroupService.list(query);
      return this.utils.response.success({ data });
    } catch (error) {
      this.logger.error("获取抽奖活动列表失败", error);
      return this.utils.response.fail({ message: "获取抽奖活动列表失败" });
    }
  }

  /**
   * 抽奖活动分页列表
   */
  @Get("/page")
  async page(@Query() query: PrizeGroupPageQueryDto) {
    try {
      const data = await this.prizeGroupService.page(query);
      return this.utils.response.success({ data });
    } catch (error) {
      this.logger.error("获取抽奖活动分页列表失败", error);
      return this.utils.response.fail({ message: "获取抽奖活动分页列表失败" });
    }
  }

  /**
   * 抽奖活动详情
   */
  @Get("/:id")
  async info(@Param("id") id: string) {
    try {
      const data = await this.prizeGroupService.info(id);
      return this.utils.response.success({ data });
    } catch (error) {
      this.logger.error("获取抽奖活动详情失败", error);
      return this.utils.response.fail({ message: "获取抽奖活动详情失败" });
    }
  }

  /**
   * 更新抽奖活动
   */
  @Put("/:id")
  async update(@Param("id") id: string, @Body() dto: PrizeGroupUpdateDto) {
    try {
      // 确保id一致
      dto.id = id;
      const user = await this.getCurrentUser();
      const success = await this.prizeGroupService.update(
        dto,
        user.userId,
        user.account
      );
      return this.utils.response.success({ data: { success } });
    } catch (error) {
      this.logger.error("更新抽奖活动失败", error);
      return this.utils.response.fail({ message: "更新抽奖活动失败" });
    }
  }

  /**
   * 取消抽奖活动
   */
  @Put("/:id/cancel")
  async cancel(@Param("id") id: string) {
    try {
      const user = await this.getCurrentUser();
      const success = await this.prizeGroupService.cancel(
        id,
        user.userId,
        user.account
      );
      return this.utils.response.success({ data: { success } });
    } catch (error) {
      this.logger.error("取消抽奖活动失败", error);
      return this.utils.response.fail({ message: "取消抽奖活动失败" });
    }
  }

  /**
   * 手动检查并更新活动状态
   * 根据当前时间自动更新所有活动的状态
   */
  @Post("/check-status")
  async checkAndUpdateStatus() {
    try {
      await this.getCurrentUser(); // 权限检查
      const count = await this.prizeGroupService.autoUpdateStatus();
      return this.utils.response.success({
        data: {
          count,
          message: `已更新${count}个活动的状态`
        }
      });
    } catch (error) {
      this.logger.error("更新活动状态失败", error);
      return this.utils.response.fail({ message: "更新活动状态失败" });
    }
  }

  /**
   * 获取各状态活动统计数据
   */
  @Get("/statistics")
  async getStatistics() {
    try {
      await this.getCurrentUser(); // 权限检查
      const data = await this.prizeGroupService.getStatusStatistics();
      return this.utils.response.success({ data });
    } catch (error) {
      this.logger.error("获取活动统计失败", error);
      return this.utils.response.fail({ message: "获取活动统计失败" });
    }
  }

  /**
   * 检查奖品组的奖品权重总和
   */
  @Get("/check-weight/:groupId")
  async checkPrizeWeight(@Param("groupId") groupId: string) {
    try {
      await this.getCurrentUser(); // 权限检查
      const result = await this.prizeGroupService.checkGroupPrizeWeight(
        groupId
      );
      return this.utils.response(result);
    } catch (error) {
      this.logger.error("检查奖品权重失败", error);
      return this.utils.response.fail({ message: "检查奖品权重失败" });
    }
  }

  /**
   * 删除抽奖活动
   */
  @Del("/:groupId")
  async remove(@Param("groupId") groupId: string) {
    try {
      await this.getCurrentUser(); // 权限检查
      const result = await this.prizeGroupService.remove(groupId);
      return this.utils.response(result);
    } catch (error) {
      this.logger.error("删除抽奖活动失败", error);
      return this.utils.response.fail({ message: "删除抽奖活动失败" });
    }
  }
}
